package com.aier.common.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Component;

import com.aier.admin.entity.SysEmail;
import com.aier.admin.entity.SysEmailError;
import com.aier.admin.entity.SysEmailHistory;
import com.aier.admin.entity.mapper.SysEmailErrorRowMapper;
import com.aier.admin.entity.mapper.SysEmailHistoryRowMapper;
import com.aier.admin.entity.mapper.SysEmailRowMapper;
import com.aier.common.dao.ICommonDAO;
import com.aier.common.service.ISysEmailService;


@Component("sysEmailService")
public class SysEmailServiceImpl_J implements ISysEmailService{

    @Resource(name = "commonDao")
    private ICommonDAO commonDao;

    public void setCommonDao(ICommonDAO commonDao) {
        this.commonDao = commonDao;
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public List<SysEmail> showAllEmail() {
        return (List<SysEmail>) commonDao.list(
                "select * from sys_email ", new Object[] {},
                new SysEmailRowMapper());
    }

    @Override
    public int updateMailSize(SysEmail se, int size) {
        if (commonDao.update(
                "update sys_email se set se.size=? where se.eid=?",
                new Object[] { size, se.getEid() }) > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public int updateForErrorEmail(SysEmail se) {
        int return_number = 1;
        SysEmailError sem = new SysEmailError();
        Timestamp cdate = new Timestamp(new Date().getTime());
        sem.setToEmail(se.getToEmail());
        sem.setType(se.getType());
        sem.setTypeChild(se.getTypeChild());
        sem.setValue(se.getValue());
        sem.setCdate(cdate);
        commonDao.insert(
                SysEmailErrorRowMapper.getPreparedStatementCreator(sem),
                new GeneratedKeyHolder());
        if (commonDao.update("delete from sys_email where eid=?",
                new Object[] { se.getEid() })==0){
            return_number = 0;
        }
        return return_number;
    }
    
    
    @Override
    public int updateForHistoryEmail(SysEmail se) {
        int return_number = 1;
        SysEmailHistory seh = new SysEmailHistory();
        Timestamp cdate = new Timestamp(new Date().getTime());
        seh.setToEmail(se.getToEmail());
        seh.setType(se.getType());
        seh.setTypeChild(se.getTypeChild());
        seh.setValue(se.getValue());
        seh.setCdate(cdate);
        commonDao.insert(
                SysEmailHistoryRowMapper.getPreparedStatementCreator(seh),
                new GeneratedKeyHolder());
        if (commonDao.update("delete from sys_email where eid=?",
                new Object[] { se.getEid() }) == 0){
            return_number = 0;
        }
        return return_number;
    }

}
